package LineCode.剑指Offer.画图让抽象形象化;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，
 * 例如，如果输入如下矩阵： 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 */
public class 顺时针打印矩阵 {

    public static void main(String[] args) {
        int [][] test = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        for (int i = 0; i < test.length; i++) {
            System.out.println(Arrays.toString(test[i]));
        }
        ArrayList<Integer> res = printMatrix(test);
        for (int i = 0; i < res.size(); i++) {
            System.out.print(res.get(i));
        }
    }

    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        return makeMatrix(matrix, new ArrayList<Integer>());
    }

    /**
     * 每add一行便 旋转矩阵
     * @param matrix
     * @param item
     * @return
     */
    public static ArrayList<Integer> makeMatrix(int [][] matrix, ArrayList<Integer> item) {
        if (matrix == null || matrix.length <= 0) return item;
        for (int i = 0; i < matrix[0].length; i++) {
            item.add(matrix[0][i]);
        }
        int [][] result = new int [matrix[0].length][matrix.length-1];
        for (int i = 0; i < matrix[0].length; i++) {
            for (int j = 0; j < matrix.length - 1; j++) {
                result[i][j] = matrix[j+1][matrix[0].length-1-i];
            }
        }
        return makeMatrix(result, item);
    }
}
